package cn.edu.scau.cmi.wuzhenzhou.service;

import java.util.Scanner;

import org.apache.ibatis.session.SqlSession;

import cn.edu.scau.cmi.wuzhenzhou.dao.StudentDao;
import cn.edu.scau.cmi.wuzhenzhou.dao.TeacherDao;
import cn.edu.scau.cmi.wuzhenzhou.domain.Student;
import cn.edu.scau.cmi.wuzhenzhou.domain.Teacher;
import cn.edu.scau.cmi.wuzhenzhou.util.ApplicationContextUtil;
import cn.edu.scau.cmi.wuzhenzhou.util.SessionFactoryUtil;

public class StudentService {

	private static SqlSession sqlSession;
	private static StudentDao studentDao;
	private static TeacherDao teacherDao;
	
	private static Scanner in;
	
	public StudentService() throws Exception{
		in = new Scanner(System.in);
		sqlSession = SessionFactoryUtil.getSqlSession();
		studentDao = sqlSession.getMapper(StudentDao.class); // 代理对象
		teacherDao = sqlSession.getMapper(TeacherDao.class);
	}
	
	/**
	 * 添加学生
	 */
	public void addStudent() {
		Student student = ApplicationContextUtil.getApplicationContext().getBean("student",Student.class);
		System.out.println("请输入学生的id:");
		student.setId(in.nextLong());
		System.out.println("请输入学生的姓名:");
		student.setName(in.next());
		studentDao.addStudent(student);
		sqlSession.commit();
		System.out.println(studentDao.selectAll());
	}
	
	/**
	 * 删除学生
	 */
	public void deleteStudent() {
		System.out.println("请输入删除学生的id");
		Long id = in.nextLong();
		studentDao.deleteStudentById(id);
		sqlSession.commit();
		System.out.println(studentDao.selectAll());
	}
	
	/**
	 * 修改学生
	 */
	public void updateStudent() {
		System.out.println("请输入要更新的学生的id:");
		Student student = studentDao.selectStudentById(in.nextLong());
		if(student==null) System.out.println("没有该学生");
		else {
			System.out.println(student);
			System.out.println("请输入修改后学生的姓名:");
			student.setName(in.next());
			studentDao.updateStudentById(student);
			System.out.println(studentDao.selectStudentById(student.getId()));
		}
	}
	
	/**
	 * 学生选择或修改指导老师
	 */
	public void updateTeacherOfStudent() {
		System.out.println("请输入学生id:");
		Student student = studentDao.selectStudentById(in.nextLong());
		if(student==null) System.out.println("没有该学生");
		else {
			System.out.println(student);
			System.out.println("请输入老师的id:");
			Teacher teacher = teacherDao.selectTeacherById(in.nextLong());
			if(teacher==null) System.out.println("没有该老师");
			else {
				student.setTeacher(teacher);
				studentDao.updateTeacherOfStudent(student);
				sqlSession.commit();
				System.out.println(studentDao.selectStudentById(student.getId()));
			}
		}
	}

}
